<template>
  <a-layout>
    <div class="layout-content">
      <a-layout-header
          class="header-shadow"
          :style="{ backgroundColor: $route.path === '/check' && !$route.query.url ? 'transparent' : '#ffffff',
          boxShadow: ($route.path === '/check' && $route.query.url) || $route.path !== '/check' ? '0 6px 10px 0 rgb(0 0 0 / 5%)':''}">
        <div class="header-content">
          <img class="header-logo" src="@/assets/img/index-img/logo.svg" alt="logo" @click="$router.push('/')"/>
          <div class="btn-search-box"
               v-show="($store.state.frontRoute.includes($route.path) && state.showSearchBox)||
               (($route.path === '/account'|| ($route.path === '/check' && $route.query.url)) && !state.showSearchBox)"
               @click="openSearchBox">
            <p>请输入网址</p>
            <div class="btn-search-icon">
              <img src="@/assets/img/account-img/search-icon.svg" alt="search-icon">
            </div>
          </div>
          <a-tabs class="nav-tab" v-model:activeKey="$route.path" @change="route=>$router.push(route)"
                  v-show="$store.state.frontRoute.includes($route.path) && !state.showSearchBox">
            <a-tab-pane v-for="item in state.menuList" :key="item.key" :tab="item.name"></a-tab-pane>
          </a-tabs>
          <div class="header-content-right" v-show="!state.showSearchDrawer">
            <!--<span class="download-app-text">App下载</span>-->
            <div class="mobile-img" v-if="$store.state.frontRoute.includes($route.path)">
              <img src="@/assets/img/account-img/shousuo-home.svg" alt="shuosuo-home" @click="state.showSearchDrawer = true">
              <img src="@/assets/img/account-img/more-home.svg" alt="more-home" @click="state.showMoreDrawer = true">
            </div>
            <a-dropdown v-model:visible="state.showNotice" :trigger="['click']" overlayClassName="notice-menu" placement="bottomRight">
              <div class="notice-img-box" v-if="$store.state.isLogin && ['/check','/account'].includes($route.path)">
                <img src="@/assets/img/account-img/notice-red-icon.svg" alt="notice-red-icon"
                     v-if="$store.state.noticeList.data?.length - $store.state.noticeList.user_fork_ids?.length > 0 && $store.state.noticeList.not_read_count !== 0">
                <img src="@/assets/img/account-img/notice-icon.svg" alt="notice-icon" v-else>
              </div>
              <template #overlay>
                <a-menu @click="event => state.showNotice = true">
                  <div class="menu-title" v-if="!state.showNoticeContent">
                    <span class="menu-text">消息盒</span>
                    <sync-outlined :class="{'disabled-click': state.synchronizing}"
                                   :spin="state.synchronizing"
                                   @click="!state.synchronizing ? getNotice() : ''"/>
                  </div>
                  <div class="notice-details" v-else>
                    <left-outlined @click="backNoticeList"/>
                    <span class="details-title">{{ state.noticeTitle }}</span>
                  </div>
                  <a-spin :spinning="state.synchronizing" tip="加载中">
                    <a-menu-item v-for="item in $store.state.noticeList.data" :key="item" @click="haveRead(item)">
                      <div class="notice-box"
                           v-if="!$store.state.noticeList.user_fork_ids.includes(item.id) && !item.showContent && !state.showNoticeContent">
                        <a-badge status="error" v-if="!$store.state.noticeList.user_read_ids.includes(item.id)"/>
                        <div class="notice-item-right"
                             :style="{'paddingLeft': $store.state.noticeList.user_read_ids.includes(item.id) ? '14px' : '0'}">
                          <div class="notice-title"
                               :class="$store.state.noticeList.user_read_ids.includes(item.id) ? 'content-text' :'main-text'">
                            <div class="notice-title-text">{{ item.title }}</div>
                            <div class="notice-time content-text">
                              {{ item.create_time.split(' ')[0] }}
                            </div>
                            <img src="@/assets/img/account-img/close-icon.png" alt="close-icon"
                                 @click.stop="removeNotice(item)" v-if="!item.deleting">
                            <loading-outlined v-else/>
                          </div>
                          <div class="notice-introduce"
                               :class="$store.state.noticeList.user_read_ids.includes(item.id) ? 'content-text' :'sub-title-text'">
                            {{ item.introduce }}
                          </div>
                        </div>
                      </div>
                      <div class="notice-content" v-show="item.showContent && state.showNoticeContent"
                           v-html="item.content"></div>
                    </a-menu-item>
                    <a-empty description="暂无消息"
                             v-show="$store.state.noticeList.data.length <= 0 && !state.synchronizing"/>
                  </a-spin>
                </a-menu>
              </template>
            </a-dropdown>
            <a-dropdown v-model:visible="state.showUserMenu" overlayClassName="account-menu" placement="bottomRight">
              <div class="round-btn" :style="{ boxShadow: $route.path !== '/check' || ($route.path === '/check' && $route.query.url) ? '0 6px 8px 0 rgb(0 0 0 / 5%)':''}" @click="state.showUserDrawer = true">
                <i class="img-icon">
                  <img src="@/assets/img/account-img/icon_gengduo.svg" alt="icon_gengduo"
                      :style="{filter: state.showUserMenu ? 'drop-shadow(#483CFF 20px 0px)' : '',left: state.showUserMenu ? '-20px' : ''}">
                </i>
                <img class="round-img" src="@/assets/img/account-img/user-icon.svg" alt="user-icon" v-if="!$store.state.isLogin">
                <img class="round-img" :src="baseUrl+'/storage/'+$store.state.userInfo.portrait" alt="portrait"
                     v-else-if="$store.state.userInfo.portrait">
                <img class="round-img" :src="$store.state.userInfo.wechat_avatar" alt="wechat_avatar"
                     v-else-if="$store.state.userInfo.wechat_avatar">
                <img class="round-img" src="@/assets/img/account-img/portrait.png" alt="portrait-default" v-else>
              </div>
              <template #overlay>
                <a-menu>
                  <a-menu-item key="login" @click="openAccount" v-if="!$store.state.isLogin">登录</a-menu-item>
                  <a-menu-item key="check" v-if="$store.state.frontRoute.includes($route.path) && $store.state.isLogin" @click="switchRouter('/check')">控制台</a-menu-item>
                  <a-menu-item key="index" v-else @click="switchRouter('/')">网站首页</a-menu-item>
                  <a-menu-item key="account" @click="switchRouter('/account')" v-if="$store.state.isLogin">账户中心</a-menu-item>
                  <a-menu-item key="help" @click="switchRouter('/help')">帮助中心</a-menu-item>
                  <a-menu-divider v-if="$store.state.isLogin"/>
                  <a-menu-item key="logout" @click="logout" v-if="$store.state.isLogin">退出登录</a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>
        </div>
        <div class="search-box-container"
             v-if="($store.state.frontRoute.includes($route.path) && !state.showSearchBox) || (['/check','/account'].includes($route.path) && state.showSearchBox)">
          <searchInput/>
        </div>
      </a-layout-header>
      <a-layout-content @click="closeSearchBox">
        <router-view></router-view>
      </a-layout-content>
    </div>
  </a-layout>

  <a-drawer v-model:visible="state.showSearchDrawer" class="mobile-search-drawer" placement="left" :closable="false">
    <template #title>
      <img src="@/assets/img/index-img/logo.svg" alt="logo" width="100"/>
    </template>
    <template #extra>
      <img src="@/assets/img/account-img/quxiao_home.svg" alt="quxiao_home" @click="state.showSearchDrawer = false">
    </template>
    <div class="mobile-search-container">
      <div class="mobile-search-box">
        <a-input v-model:value="$store.state.queryForm.url"
                 placeholder="请输入带http://或https://的链接"
                 @click="searchData.menuTitle = '历史搜索'"
                 allowClear
                 @pressEnter="queryLink"
        >
          <template #prefix>
            <img src="@/assets/img/account-img/chazhao_default.svg" alt="chazhao_default">
          </template>
        </a-input>
        <a-divider type="vertical" class="search-line"/>
        <div class="mobile-region" @click="searchData.menuTitle = '选择地域'">
          <img src="@/assets/img/account-img/location_shousuo.svg" alt="location_shousuo">
          {{ searchData.region }}
        </div>
      </div>
    </div>
    <div class="mobile-history">
      <div class="mobile-history-header">
        <h3>{{ searchData.menuTitle }}</h3>
        <a-button type="text"
                  @click="$store.dispatch('removeHistory','all')"
                  v-show="searchData.menuTitle === '历史搜索' && $store.state.historyRecord.length > 0">
          <template #icon>
            <delete-outlined />
          </template>
          清除记录
        </a-button>
      </div>
      <div class="mobile-history-content">
        <span class="mobile-history-item"
              v-for="item in $store.state.historyRecord" :key="item"
              v-show="searchData.menuTitle === '历史搜索'"
              @click="$store.state.queryForm.url = item">
        {{ item }}
      </span>
      </div>
      <div class="mobile-region-container">
        <div :class="{'mobile-region-item':true,'mobile-region-active': searchData.region === item}"
             v-for="item in $store.state.provinceList" :key="item"
             v-show="searchData.menuTitle === '选择地域'"
             @click="searchData.region = item">
          {{ item }}
        </div>
      </div>
    </div>
  </a-drawer>

  <a-drawer v-model:visible="state.showMoreDrawer" class="mobile-more-drawer" placement="top" :closable="false">
    <template #title>
      <img src="@/assets/img/index-img/logo.svg" alt="logo" width="100"/>
    </template>
    <template #extra>
      <img src="@/assets/img/account-img/quxiao_home.svg" alt="quxiao_home" @click="state.showMoreDrawer = false">
    </template>
    <ul class="mobile-menu-list">
      <li v-for="item in state.menuList" :key="item.key" @click="switchRouter(item.key)">{{ item.name }}</li>
    </ul>
  </a-drawer>

  <a-drawer v-model:visible="state.showUserDrawer" class="mobile-user-drawer" placement="right" :closable="false">
    <template #title>
      <img src="@/assets/img/index-img/logo.svg" alt="logo" width="100"/>
    </template>
    <template #extra>
      <img src="@/assets/img/account-img/quxiao_home.svg" alt="quxiao_home" @click="state.showUserDrawer = false">
    </template>
    <ul class="mobile-menu-list">
      <li v-if="['/','/help','/about','/product'].includes($route.path) && $store.state.isLogin" @click="switchRouter('/check')">控制台</li>
      <li v-else @click="switchRouter('/')">网站首页</li>
      <li @click="switchRouter('/account')" v-if="$store.state.isLogin">账户中心</li>
      <li @click="switchRouter('/help')">帮助中心</li>

    </ul>
<!--    <a-row class="user-btn-box" :gutter="8">-->
<!--      <a-col :span="12">-->
<!--        <a-button type="primary" @click="openAccount">免费注册</a-button>-->
<!--      </a-col>-->
<!--      <a-col :span="12">-->
<!--        <a-button type="primary" ghost @click="openAccount">登录</a-button>-->
<!--      </a-col>-->
<!--    </a-row>-->
    <div class="user-btn-box">
      <a-button type="primary" v-show="!$store.state.isLogin" @click="openAccount">登录</a-button>
      <a-button type="primary" ghost v-show="$store.state.isLogin" @click="logout">退出登录</a-button>
    </div>
  </a-drawer>

  <a-modal v-model:visible="state.showAccount" :footer="false" getContainer=".ant-layout" width="760px"
           @cancel="closeAccount" centered destroyOnClose>
    <template #closeIcon>
      <img src="@/assets/img/account-img/close-icon.png" alt="close-icon">
    </template>
    <a-row class="account-box">
      <a-col :xs="0" :sm="11" :md="11" class="account-box-left">
      </a-col>
      <a-col :xs="24" :sm="13" :md="13" class="account-content">
        <a-tabs :default-active-key="state.activeTab" @change="accountTabChange">
          <a-tab-pane key="weixin" v-if="!retrieveData.isShow && !registerData.isShow" tab="微信登录">
            <p class="sub-title-text">首次扫码将自动完成微信注册</p>
            <a-spin tip="加载二维码中..." :spinning="state.gettingQrcode">
              <div class="qrcode-img-box">
                <qrcode-vue :value="state.wechatUrl" :size="158" @click="getWechatUrl"/>
                <div class="qrcode-cover" v-if="!state.qrcodeIsVaild" @click="getWechatUrl">
                  <img src="@/assets/img/account-img/refresh-icon.png" alt="refresh" width="32" height="29">
                  <span class="main-text">二维码已失效</span>
                  <a-button type="text" class="primary-text">点击刷新</a-button>
                </div>
              </div>
            </a-spin>
            <p>请使用微信扫描二维码登录“检查链接”</p>
            <p>登录即表示已阅读并同意<span class="primary-text"> 用户协议 </span>和<span class="primary-text"> 隐私政策</span></p>
          </a-tab-pane>
          <a-tab-pane key="login" v-if="!retrieveData.isShow && !registerData.isShow" tab="账号登录">
            <a-form ref="loginFormRef" :model="loginData.formData" @finish="submitLogin(loginData.formData)"
                    :rules="$store.state.rules" @finishFailed="formFailed">
              <a-form-item name="mobile" :hasFeedback="true" :rules="[{ required: true, validator: validatePhone }]">
                <a-input placeholder="请输入您的手机号" allowClear v-model:value.trim="loginData.formData.mobile"/>
              </a-form-item>
              <a-form-item name="password" :rules="[{ required: true, message: '密码不能为空' }]"
                           v-if="loginMethodsText === '免密码登录'">
                <a-input-password allowClear v-model:value.trim="loginData.formData.password" placeholder="请输入您的密码"/>
              </a-form-item>
              <a-form-item class="code-form-item" name="code" v-else>
                <div class="code-input-box">
                  <a-input allowClear v-model:value="loginData.formData.code" placeholder="请输入验证码"/>
                  <a-divider type="vertical"/>
                  <a-button type="text" class="success-text" :disabled="disabledGetYzmBtn(loginData.formData.mobile)"
                            @click="$store.commit('getYzm',loginData.formData.mobile)"
                            v-if="!$store.state.showCountDown">
                    发送验证码
                  </a-button>
                  <div class="getting-code" v-else>
                    {{ $store.state.countDownNum }}s后重新发送
                  </div>
                </div>
              </a-form-item>
              <a-form-item>
                <a-button type="primary" html-type="submit" :loading="loginData.logining">登录</a-button>
              </a-form-item>
              <div class="form-menu">
                <a-checkbox v-model:checked="state.agreement">
                  我已阅读并同意<span class="primary-text"> 用户协议 </span>及<span class="primary-text"> 审核规则</span>
                </a-checkbox>
                <div class="form-menu-right">
                  <a-button type="text" class="content-text" @click="retrieveData.isShow = true">忘记密码</a-button>
                  <a-divider type="vertical"/>
                  <a-button type="text" class="content-text" @click="registerData.isShow = true">注册</a-button>
                </div>
              </div>
            </a-form>
            <div class="form-bottom">
              <p>{{ loginMethodsText }}</p>
              <div class="form-bottom-icon" @click="changeLoginMethod" v-show="loginMethodsText === '免密码登录'">
                <img src="@/assets/img/account-img/phone-icon.png" alt="phone-icon">
              </div>
              <img src="@/assets/img/account-img/lock-icon.png" alt="lock-icon" width="44" height="44"
                   v-show="loginMethodsText === '密码登录'" @click="changeLoginMethod">
            </div>
          </a-tab-pane>
          <a-tab-pane key="register" v-if="registerData.isShow" tab="注册">
            <a-form ref="registerFormRef" :model="registerData.formData" :rules="$store.state.rules" @finish="submitRegister"
                    @finishFailed="formFailed">
              <div v-if="!registerData.registerOk">
                <a-form-item name="mobile" :hasFeedback="true"
                             :rules="[{ required: true, validator: validateRegPhone }]">
                  <a-input placeholder="请输入您的手机号" allowClear v-model:value.trim="registerData.formData.mobile"/>
                </a-form-item>
                <a-form-item class="code-form-item" name="code">
                  <div class="code-input-box">
                    <a-input placeholder="请输入验证码" allowClear v-model:value="registerData.formData.code"/>
                    <a-divider type="vertical"/>
                    <a-button type="text" class="success-text" :disabled="registerData.disabledRegYzm"
                              @click="$store.commit('getYzm',registerData.formData.mobile)"
                              v-if="!$store.state.showCountDown">发送验证码
                    </a-button>
                    <div class="getting-code" v-else>
                      {{ $store.state.countDownNum }}s后重新发送
                    </div>
                  </div>
                </a-form-item>
                <a-form-item name="password" :hasFeedback="true">
                  <a-input placeholder="请设置8-16位包含字母和数字的密码" allowClear
                           v-model:value.trim="registerData.formData.password"/>
                </a-form-item>
              </div>
              <div class="step-complete" v-else>
                <img src="@/assets/img/account-img/complete-icon.png" alt="complete-icon">
                <p>注册成功</p>
                <p>您已成功注册账号，正在自动登录中...</p>
              </div>
              <a-form-item v-if="!registerData.registerOk">
                <a-button type="primary" html-type="submit" :loading="registerData.registering">注册</a-button>
              </a-form-item>
              <a-form-item v-if="!registerData.registerOk" class="form-menu">
                <a-checkbox v-model:checked="state.agreement">
                  我已阅读并同意<span class="primary-text"> 用户协议 </span>及<span class="primary-text"> 审核规则</span>
                </a-checkbox>
              </a-form-item>
            </a-form>
            <div class="existing-account" v-if="!registerData.registerOk">
              已有账号，
              <a-button type="text" class="primary-text" @click="backLogin('register')">立即登录</a-button>
            </div>
          </a-tab-pane>
          <a-tab-pane key="retrieve" v-if="retrieveData.isShow" tab="找回密码">
            <a-form ref="retrieveFormRef" :model="retrieveData.formData" :rules="$store.state.rules" @finish="submitRetrieve"
                    @finishFailed="formFailed">
              <div v-if="!retrieveData.findPwdOk">
                <a-form-item name="mobile" :hasFeedback="true" :rules="[{ required: true, validator: validatePhone }]">
                  <a-input allowClear v-model:value.trim="retrieveData.formData.mobile" placeholder="请输入您的手机号"/>
                </a-form-item>
                <a-form-item class="code-form-item" name="code">
                  <div class="code-input-box">
                    <a-input allowClear v-model:value="retrieveData.formData.code" placeholder="请输入验证码"/>
                    <a-divider type="vertical"/>
                    <a-button type="text" class="success-text"
                              :disabled="disabledGetYzmBtn(retrieveData.formData.mobile)"
                              @click="$store.commit('getYzm',retrieveData.formData.mobile)"
                              v-if="!$store.state.showCountDown">发送验证码
                    </a-button>
                    <div class="getting-code" v-else>
                      {{ $store.state.countDownNum }}s后重新发送
                    </div>
                  </div>
                </a-form-item>
                <a-form-item name="password" :hasFeedback="true">
                  <a-input allowClear v-model:value.trim="retrieveData.formData.password"
                           placeholder="请输入8-16位包含字母和数字的密码"/>
                </a-form-item>
              </div>
              <div class="step-complete" v-else>
                <img src="@/assets/img/account-img/complete-icon.png" alt="complete-icon">
                <p>修改密码成功</p>
                <p>您已成功修改新密码，下次可使用新密码登录！</p>
                <a-button type="primary" @click="backLogin('retrieve')">马上登录</a-button>
              </div>
              <a-form-item v-if="!retrieveData.findPwdOk">
                <a-button type="primary" html-type="submit" :loading="retrieveData.retrieving">立即找回</a-button>
              </a-form-item>
            </a-form>
            <div class="existing-account" v-show="!retrieveData.findPwdOk">
              已有账号，
              <a-button type="text" class="primary-text" @click="backLogin('retrieve')">立即登录</a-button>
            </div>
          </a-tab-pane>
        </a-tabs>
      </a-col>
    </a-row>
  </a-modal>
</template>

<script setup>
import searchInput from '@/components/searchInput'
import {reactive, ref, getCurrentInstance, onMounted, provide, onUnmounted, createVNode} from 'vue'
import {
  LoadingOutlined,
  LeftOutlined,
  SyncOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons-vue'
import {onBeforeRouteUpdate, useRouter, useRoute} from 'vue-router'
import {validatePhone, formFailed, disabledGetYzmBtn} from '@/plugin/validate'
import {baseUrl, registerApi, loginApi, forgetPwd, getWechat, getStatus, getNoticeById, getHomeNotice, forkNoticeById, mobileIsReg} from '@/axios'
import {useStore} from 'vuex'
import {encryptedData} from '@/plugin/encrypted'
import QrcodeVue from 'qrcode.vue'
import {Modal} from "ant-design-vue";
const {proxy} = getCurrentInstance()
const router = useRouter()
const route = useRoute()
const store = useStore()

const state = reactive({
  showMoreDrawer: false,
  showSearchDrawer: false,
  showUserDrawer: false,
  showSearchBox: false,
  showNotice: false,
  showNoticeContent: false,
  synchronizing: false,
  noticeTitle: '',
  showAccount: false,
  showUserMenu: false,
  activeTab: '',
  agreement: true,
  gettingQrcode: false,
  wechatUrl: '',
  qrcodeIsVaild: true,
  scrollDirection: null,
  menuList: [
    {name:'首页', key:'/'},
    {name:'产品介绍', key:'/product'},
    {name:'帮助中心', key:'/help'},
    {name:'关于我们', key:'/about'}
  ],
})
provide('showSearchBox',state.showSearchBox)
provide('updateShowSearchBox',val=>{
  state.showNotice = false
  state.showSearchBox = val
})
store.dispatch('getUserInfo')

onMounted(() => {
  document.addEventListener('scroll', scrollFn, true)
})

onUnmounted(()=>{
  document.removeEventListener('scroll', scrollFn, true)
})

onBeforeRouteUpdate(to => {
  // to.path !== '/account' && store.state.isLogin ? store.commit('checkIsBindMobile') : ''
  state.showSearchBox = false
  store.state.frontRoute.includes(to.path) ? window.scrollTo(0, 0) : ''
})

let scrollActionY = 'undefined'
const scrollFn =  event=> {
  if (typeof scrollActionY == 'undefined') {
    scrollActionY = window.pageYOffset
  }
  let diffY = scrollActionY - window.pageYOffset
  if (diffY < 0) {
    state.scrollDirection = 'down'
    route.path !== '/check' ? state.showSearchBox = true : ''
  } else if (diffY > 0) {
    state.scrollDirection = 'up'
    if(window.pageYOffset <= 80){
      route.path !== '/check' ? state.showSearchBox = false : ''
    }
  }
  scrollActionY = window.pageYOffset
}

const searchData = reactive({
  menuTitle: '历史搜索',
  region: '地区'
})
const queryLink = ()=>{
  // if(!store.state.userInfo.mobile && this.state.isLogin) return store.commit('checkIsBindMobile')
  if(!store.state.isLogin) return proxy.$message.error('您未登录或已超时，请先登录后，再进行操作。')
  if(!store.state.queryForm.url) return proxy.$message.error('链接不能为空。')
  if(!store.state.urlReg.test(store.state.queryForm.url)) return proxy.$message.error('链接格式有误。')
  store.dispatch('queryLink')
}

const getNotice = async () => {
  state.synchronizing = true
  // store.commit('changeState',['noticeList', {}])
  const res = await getHomeNotice()
  res.code === 0 ? store.commit('changeState', ['noticeList', res.data]) : proxy.$message.error(res.msg)
  state.synchronizing = false
}

const haveRead = async item => {
  const {id, title} = item
  state.showNoticeContent = true
  item.showContent = true
  state.noticeTitle = title
  if (!store.state.noticeList.user_read_ids.includes(id)) {
    const res = await getNoticeById({id})
    if (res.code === 0) {
      let newNoticeList = store.state.noticeList
      newNoticeList.user_read_ids.push(id)
      store.commit('changeState', ['noticeList', newNoticeList])
    } else {
      proxy.$message.error(res.msg)
    }
  }
}

const backNoticeList = () => {
  state.showNoticeContent = false
  let newNoticeList = store.state.noticeList
  newNoticeList.data.forEach(item => item.showContent ? delete item.showContent : '')
  store.commit('changeState', ['noticeList', newNoticeList])
}

const removeNotice = async item => {
  item.deleting = true
  const res = await forkNoticeById({id: item.id})
  if (res.code === 0) {
    proxy.$message.success(res.msg)
    let newNoticeList = store.state.noticeList
    let index = newNoticeList.data.indexOf(item)
    if (index !== -1) {
      newNoticeList.data.splice(index, 1)
      store.commit('changeState', ['noticeList', newNoticeList])
    }
  } else {
    proxy.$message.error(res.msg)
  }
  item.deleting = false
}

const openSearchBox = () => {
  if(store.state.frontRoute.includes(route.path)){
    state.showSearchBox = false
  }else if(['/check', '/account'].includes(route.path)){
    state.showSearchBox = true
  }
}

const closeSearchBox = ()=>{
  state.showNotice = false
  if(['/help','/about','/product'].includes(route.path) && (state.scrollDirection === 'down' || (window.pageYOffset >= 80&&state.scrollDirection === 'up'))){
    state.showSearchBox = true
  } else if (['/check', '/account'].includes(route.path)) {
    state.showSearchBox = false
  }
}

const openAccount = () => {
  state.showUserMenu = false
  state.showUserDrawer = false
  if (!store.state.isLogin) {
    state.showAccount = true
    getWechatUrl()
  }
}

const accountTabChange = tab => {
  closeAccount()
  tab === 'weixin' ? getWechatUrl() : ''
}

let qrcodeInterval = null
const getWechatUrl = async () => {
  state.gettingQrcode = true
  clearInterval(qrcodeInterval)
  const wechatRes = await getWechat()
  if (wechatRes.code === 1) {
    state.gettingQrcode = false
    state.qrcodeIsVaild = true
    let time = 60
    qrcodeInterval = setInterval(() => {
      if (time <= 1) {
        state.qrcodeIsVaild = false
        clearInterval(qrcodeInterval)
      } else {
        time--
        getStatus({token: wechatRes.token}).then(res => {
          if (res.code === 0) {
            clearInterval(qrcodeInterval)
            localStorage.setItem('userToken', res.data.token)
            state.showAccount = false
            store.dispatch('getUserInfo')
            proxy.$message.success(res.msg)
            setTimeout(()=>{
              router.push('/check')
              usePcTips()
            },300)
          }
        })
      }
    }, 1000)
    state.wechatUrl = wechatRes.url
  }
}

const closeAccount = () => {
  clearInterval(qrcodeInterval)
  document.querySelector('.code-input-box') ? document.querySelector('.code-input-box').style.borderColor = '#d9d9d9' : ''
  registerData.registerOk = false
  retrieveData.findPwdOk = false
  proxy.$refs.loginFormRef ? proxy.$refs.loginFormRef.resetFields() : ''
  proxy.$refs.registerFormRef ? proxy.$refs.registerFormRef.resetFields() : ''
  proxy.$refs.retrieveFormRef ? proxy.$refs.retrieveFormRef.resetFields() : ''
}

const loginData = reactive({
  logining: false,
  formData: {
    type: 1,
    mobile: '',
    password: '',
    code: ''
  }
})

const submitLogin = async formData => {
  loginData.logining = true
  const res = await loginApi({key: encryptedData(JSON.stringify(formData))})
  if (res.code === 0) {
    localStorage.setItem('userToken', res.data[0])
    state.showAccount = false
    closeAccount()
    proxy.$message.success(res.msg)
    store.commit('changeState', ['isLogin', true])
    store.commit('changeState', ['userInfo', res.data[1]])
    store.commit('changeState', ['passwordSet', res.data.pass_set])
    store.commit('resetCountDown')
    await getNotice()
    await router.push('/check')
    usePcTips()
  } else {
    proxy.$message.error(res.msg)
  }
  loginData.logining = false
}

const usePcTips = ()=>{
  if(window.innerWidth <= 768){
    Modal.info({
      title: '建议使用PC端以获得更好的体验。',
      centered: true,
    })
  }
}

let loginMethodsText = ref('免密码登录')
const changeLoginMethod = () => {
  if (loginMethodsText.value === '免密码登录') {
    loginMethodsText.value = '密码登录'
    loginData.formData.type = 2
  } else {
    loginMethodsText.value = '免密码登录'
    loginData.formData.type = 1
  }
}

const registerData = reactive({
  registering: false,
  isShow: false,
  registerOk: false,
  formData: {
    mobile: '',
    password: '',
    code: ''
  },
  disabledRegYzm: true
})

const validateRegPhone = async (rules, value) => {
  registerData.disabledRegYzm = true
  if (value === '') return Promise.reject('手机号不能为空')
  if (!store.state.phoneReg.test(value)) return Promise.reject('请输入正确的手机号')
  const res = await mobileIsReg({mobile: value})
  if (res.code !== 0) return Promise.reject(res.msg)
  registerData.disabledRegYzm = false
  await Promise.resolve()
}

const submitRegister = async () => {
  registerData.registering = true
  const res = await registerApi({key: encryptedData(JSON.stringify(registerData.formData))})
  if (res.code === 0) {
    proxy.$message.success(res.msg)
    registerData.registerOk = true
    setTimeout(() => {
      submitLogin({type: 1, mobile: registerData.formData.mobile, password: registerData.formData.password})
      store.commit('resetCountDown')
    }, 1500)
  } else {
    proxy.$message.error(res.msg)
  }
  registerData.registering = false
}

const retrieveData = reactive({
  retrieving: false,
  isShow: false,
  findPwdOk: false,
  formData: {
    mobile: '',
    password: '',
    code: ''
  }
})

const submitRetrieve = async () => {
  retrieveData.retrieving = true
  const res = await forgetPwd({key: encryptedData(JSON.stringify(retrieveData.formData))})
  if (res.code === 1) {
    proxy.$message.success(res.msg)
    retrieveData.findPwdOk = true
    store.commit('resetCountDown')
  } else {
    proxy.$message.error(res.msg)
  }
  retrieveData.retrieving = false
}

const backLogin = type => {
  switch (type) {
    case 'register':
      registerData.isShow = false
      break
    case 'retrieve':
      retrieveData.isShow = false
      break
  }
}

const switchRouter = path => {
  router.push(path)
  state.showUserMenu = false
  state.showMoreDrawer = false
  state.showUserDrawer = false
}

const logout = () => {
  store.commit('logout')
  state.showUserMenu = false
  state.showUserDrawer = false
}
</script>

<style lang="less" scoped>
.ant-layout {
  min-height: 100vh;

  &:deep(.layout-content) {
    min-height: 100vh;

    .ant-layout-header {
      width: 100%;
      height: 80px;
      line-height: unset;
      padding: 0 20px;
      position: fixed;
      left: 0;
      top: 0;
      z-index: 5;

      .header-content {
        max-width: 1632px;
        height: inherit;
        margin: 0 auto;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .header-logo{
          width: 120px;
        }
        img {
          cursor: pointer;
        }

        .btn-search-box {
          width: 260px;
          height: 42px;
          border: 1px solid @split-line;
          border-radius: 24px;
          padding: 0 8px 0 18px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          cursor: pointer;

          h3 {
            cursor: pointer;
          }

          p {
            color: @content;
            display: flex;
            align-items: center;
            margin-bottom: 0;
          }

          .btn-search-icon {
            width: 31px;
            height: 30px;
            background-color: @primary;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;

            img {
              width: 20px;
              height: 20px;
            }
          }
        }

        .ant-tabs {
          .ant-tabs-nav {
            margin-bottom: 0;

            .ant-tabs-nav-wrap {
              .ant-tabs-nav-list {
                .ant-tabs-tab {
                  padding-bottom: 8px;
                  margin-right: 0;

                  &:not(:nth-child(1)) {
                    margin-left: 80px;
                  }

                  .ant-tabs-tab-btn {
                    font-size: 16px;
                    color: @text;
                  }
                }
              }
            }
          }
        }

        .ant-input-affix-wrapper-focused {
          box-shadow: unset;
          border: 1px solid @primary;
        }

        .header-content-right {
          display: flex;
          align-items: center;
          .mobile-img{
            display: none;
            img{
              width: 26px;
              height: 26px;
              margin-right: 16px;
            }
          }
          .download-app-text {
            font-size: 16px;
            font-weight: 500;
            color: @text;
            cursor: pointer;
            margin-right: 81px;
          }

          .round-btn {
            width: 84px;
            height: 44px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 6px 6px 6px 12px;
            border-radius: 22px;
            border: 1px solid #DFDFDF;
            cursor: pointer;

            .anticon-menu {
              font-size: 20px;
              color: @sub-title;
            }
            .round-img {
              width: 32px;
              height: 32px;
              border-radius: 50%;
            }
            i.img-icon{
              width: 20px;
              overflow: hidden;
              cursor: pointer;
              img{
                position: relative;
                border-right: 20px solid transparent;
              }
            }
          }
          .notice-img-box{
            margin-right: 32px;
          }
        }
      }
    }

    .search-box-container {
      width: 100%;
      position: fixed;
      left: 0;
      top: 80px;
      z-index: 10;
      background-color: #FFFFFF;
      padding-bottom: 20px;
      box-shadow: 0 6px 10px rgba(0, 0, 0, 0.05);
    }
  }

  &:deep(.ant-modal-root) {
    .ant-modal-wrap {
      .ant-modal {
        padding: 0 20px;

        .ant-modal-content {
          border-radius: 8px;
          overflow: hidden;

          .ant-modal-body {
            padding: 0;

            .account-box {
              height: 500px;

              .account-box-left {
                background: url("../assets/img/account-img/login-bg.png") no-repeat;
                background-size: 100% 100%;
              }

              .account-content {
                padding: 45px 32px 30px;

                .ant-tabs {
                  .ant-tabs-nav {
                    margin-bottom: 30px;

                    .ant-tabs-nav-wrap {
                      .ant-tabs-nav-list {
                        width: 100%;
                        border-bottom: 1px solid @split-line;
                      }
                    }
                  }

                  .ant-tabs-content-holder {
                    .ant-tabs-content {
                      .ant-tabs-tabpane {
                        &:nth-of-type(1) {
                          text-align: center;

                          p {
                            font-size: 12px;
                            margin-bottom: 0;

                            &:nth-last-of-type(1) {
                              margin-top: 18px;
                            }

                            span {
                              cursor: pointer;
                              transition: color 0.15s ease;

                              &:hover {
                                color: @primary;
                              }
                            }
                          }
                        }

                        .ant-form {
                          .ant-form-item {
                            .ant-form-item-control {
                              .ant-form-item-control-input {
                                .ant-form-item-control-input-content {
                                  .ant-btn-primary {
                                    width: 100%;
                                    border-radius: 2px;
                                    height: 40px;
                                  }
                                }
                              }
                            }
                          }

                          .form-menu {
                            display: flex;
                            justify-content: space-between;
                            .ant-checkbox-wrapper {
                              font-size: 12px;
                              display: flex;
                              align-items: center;

                              .ant-checkbox {
                                vertical-align: middle;
                                top: 0;

                                .ant-checkbox-inner {
                                  width: 13px;
                                  height: 13px;
                                }

                                + span {
                                  color: @content;
                                }
                              }
                            }

                            .form-menu-right {
                              display: flex;
                              align-items: center;

                              .ant-btn-text {
                                line-height: unset;
                                height: unset;
                                padding: 0;
                                font-size: 12px;

                                &:hover {
                                  color: @sub-title;
                                }
                              }

                              .ant-divider-vertical {
                                top: 0;
                                border-color: @split-line;
                              }
                            }
                          }
                        }

                        .step-complete {
                          margin-top: 20px;

                          img {
                            margin-bottom: 20px;
                          }

                          p {
                            font-size: 14px;
                          }

                          .ant-btn-primary {
                            margin-top: 20px;
                          }
                        }

                        .existing-account {
                          color: @sub-title;
                          font-size: 12px;
                          text-align: center;
                          display: flex;
                          align-items: center;
                          justify-content: center;

                          .ant-btn-text {
                            font-size: 12px;
                          }
                        }
                      }
                    }
                  }

                  .ant-tabs-tab {
                    + .ant-tabs-tab {
                      margin: 0 0 0 40px;
                    }
                  }

                  .ant-tabs-ink-bar {
                    height: 2px !important;
                    bottom: -2px;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>

<style lang="less">
.account-menu {
  .ant-dropdown-content {
    .ant-dropdown-menu {
      width: 150px;
      margin-top: 5px;
      border-radius: 8px;
      box-shadow: 0 0 10px 2px rgba(0, 0, 0, 0.05);

      .ant-dropdown-menu-item {
        padding: 8px 20px;

        .ant-dropdown-menu-title-content {
          color: @sub-title;
        }
      }
    }
  }
}

.notice-menu {
  border-radius: 8px;
  box-shadow: 0 0 15px 2px rgba(0, 0, 0, 0.1);
  overflow: hidden;

  .ant-dropdown-content {
    border-radius: 8px;
    overflow: hidden;

    .ant-dropdown-menu {
      width: 304px;
      padding: 0;
      border-radius: 8px;
      max-height: 450px;
      overflow: hidden;

      .menu-title {
        width: 100%;
        height: 44px;
        border-bottom: 1px solid @split-line;
        padding: 0 20px;
        position: relative;

        .menu-text {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }

        .anticon-sync {
          position: absolute;
          right: 20px;
          top: 50%;
          transform: translateY(-50%);
          cursor: pointer;
        }
      }

      .ant-spin-nested-loading {
        position: unset;

        .ant-spin {
          padding-top: 44px;

          .ant-spin-dot,
          .ant-spin-text {
            top: 55%;
          }
        }
      }

      .notice-details {
        width: 100%;
        height: 44px;
        border-bottom: 1px solid @split-line;
        line-height: unset;
        padding: 0 20px;
        position: relative;

        .anticon-left {
          position: absolute;
          left: 20px;
          top: 50%;
          transform: translateY(-50%);
          cursor: pointer;
          z-index: 2;
        }

        .details-title {
          width: calc(100% - 54px);
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          text-align: center;
          padding: 0 30px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .ant-empty {
        margin-top: 15px;
      }

      .ant-dropdown-menu-item {
        padding: 0;

        &:hover {
          .ant-dropdown-menu-title-content {
            .notice-box {
              .notice-item-right {
                .notice-title {
                  img {
                    visibility: visible;
                  }
                }
              }
            }
          }
        }

        .ant-dropdown-menu-title-content {
          .notice-box {
            display: flex;
            padding: 16px 20px 16px 20px;
            overflow: hidden;

            .notice-item-right {
              width: 100%;

              .notice-title {
                font-size: 14px;
                //font-weight: 600;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .notice-title-text {
                  width: 160px;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                  font-size: 16px;
                  font-weight: 600;
                }

                .notice-time {
                  font-size: 12px;
                  margin-right: 5px;
                }

                img {
                  visibility: hidden;
                  width: 16px;
                  height: 16px;
                  border-radius: 50%;
                  padding: 2px;
                  transition: all .2s;

                  &:hover {
                    opacity: 0.85;
                    background-color: rgba(0, 0, 0, 0.1);
                  }
                }
              }

              .notice-introduce {
                width: 244px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                margin-top: 5px;
              }
            }
          }

          .notice-content {
            padding: 16px 26px 16px 20px;

            p {
              margin: 0;
            }
          }
        }
      }
    }
  }
}

.ant-drawer{
  .ant-drawer-content-wrapper{
    width: 100%!important;
    .ant-drawer-content{
      .ant-drawer-wrapper-body{
        .ant-drawer-header{
          height: 60px;
          .ant-drawer-extra{
            img{
              cursor: pointer;
            }
          }
        }
        .ant-drawer-body{
          padding: 0;
          overflow: hidden;
          .mobile-menu-list{
            padding: 0 10px;
            color: @sub-title;
            margin-bottom: 0;
            li{
              padding: 20px 6px;
              border-bottom: 1px solid #F6F7FB;
            }
          }
          .user-btn-box{
            margin-top: 80px;
            display: flex;
            justify-content: center;
            padding: 0 16px;
            .ant-btn{
              width: 168px;
              //width: 100%;
              height: 36px;
              font-size: 12px;
            }
            .ant-btn-background-ghost{
              border-color: @primary;
              color: @primary;
            }
          }
        }
      }
    }
  }
}

.mobile-more-drawer{
  .ant-drawer-content-wrapper{
    height: 100%!important;
    .ant-drawer-content{
      .ant-drawer-wrapper-body{
        .ant-drawer-body{
          .ant-drawer-header{
            border-color: #F6F7FB;
          }
        }
      }
    }
  }
}

.mobile-search-drawer{
  .ant-drawer-content-wrapper{
    .ant-drawer-content{
      .ant-drawer-wrapper-body{
        .ant-drawer-header{
          border-bottom: none;
        }
        .ant-drawer-body{
          padding: 0;
          .mobile-search-container{
            height: 72px;
            background: #F6F7FB;
            padding: 16px 14px;
            .mobile-search-box{
              width: 100%;
              height: 100%;
              display: flex;
              align-items: center;
              justify-content: space-between;
              background-color: #FFFFFF;
              border-radius: 20px;
              .ant-input-affix-wrapper{
                height: 100%;
                border: none;
                background-color: transparent;
                .ant-input{
                  background-color: transparent;
                  &::placeholder{
                    font-size: 12px;
                    color: @tips-text;
                  }
                }
              }
              .ant-divider{
                margin: 0;
              }
              .ant-input-affix-wrapper-focused{
                box-shadow: unset!important;
              }
              .mobile-region{
                width: 80px;
                text-align: center;
                color: @text;
                font-size: 12px;
                display: flex;
                align-items: center;
                justify-content: center;
                img{
                  margin-right: 5px;
                }
              }
            }
          }
          .mobile-history{
            padding: 20px 14px;
            width: 100%;
            height: calc(100% - 72px);
            .mobile-history-header{
              display: flex;
              align-items: center;
              justify-content: space-between;
              margin-bottom: 20px;
              h3{
                margin: 0;
                font-size: 14px;
                font-weight: 500;
                color: @sub-title;
              }
              .ant-btn{
                font-size: 12px;
                color: @content;
                height: unset;
                .anticon + span, .ant-btn > span + .anticon{
                  margin-left: 5px;
                }
              }
            }
            .mobile-history-item,
            .mobile-region-item{
              font-size: 12px;
              background-color: #F6F7FB;
              color: @content;
            }
            .mobile-history-content{
              .mobile-history-item{
                display: inline-block;
                height: 24px;
                margin-right: 12px;
                margin-bottom: 13px;
                padding: 0 13px;
                line-height: 24px;
                border-radius: 4px;
              }
            }
            .mobile-region-container{
              display: grid;
              grid-template-columns: repeat(auto-fill, 78px) minmax(60px,78px);
              grid-gap: 12px 12px;
              justify-content: space-evenly;
              .mobile-region-item{
                height: 28px;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: all .2s;
              }
              .mobile-region-active{
                color: @primary;
                background-color: #EAE9FF;
              }
            }
          }
        }
      }
    }
  }
}

.mobile-user-drawer{
  display: none;
}
.ant-input-suffix{
  .anticon-close-circle{
    font-size: 14px;
  }
}
</style>
